import os
import pymysql

from utils.logutil import getlog
from utils.readutil import Readdata


class MysqlUtil:
    def __init__(self):
        self.mysql_config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config",
                                              "setting.ini")
        self.mysql_config_data = Readdata().read_ini(self.mysql_config_path)["mysql"]
        self.mysql_data = {
            "host": self.mysql_config_data["MYSQL_HOST"],
            "port": int(self.mysql_config_data["MYSQL_PORT"]),
            "user": self.mysql_config_data["MYSQL_USER"],
            "passwd": self.mysql_config_data["MYSQL_PASSWD"],
            "db": self.mysql_config_data["MYSQL_DB"]
        }
        self.conn = pymysql.connect(**self.mysql_data, autocommit=True)
        self.cor = self.conn.cursor()

    def __del__(self):
        self.cor.close()
        self.conn.close()

    def searchone(self, sql):
        getlog.info(f"搜索的sql语句是：>>>>>>>>>>>>>>>>{sql}")
        self.cor.execute(sql)
        result = self.cor.fetchone()
        getlog.info(f"搜索的结果是：>>>>>>>>>>>>>>>>{result}")
        return result

    def searchall(self, sql):
        getlog.info(f"搜索的sql语句是：>>>>>>>>>>>>>>>>{sql}")
        self.cor.execute(sql)
        result = self.cor.fetchall()
        getlog.info(f"搜索的结果是：>>>>>>>>>>>>>>>>{result}")
        return result

    def do_sql(self, sql):
        try:
            getlog.info(f"执行的sql语句是：>>>>>>>>>>>>>>>>{sql}")
            self.cor.execute(sql)
            self.conn.commit()
        except Exception as e:
            getlog.error(f"执行的sql有错误，错误：{e}")
